﻿using iChip.Hostpots.Commons;
using iChip.Hostpots.Models;
using iChip.Hotspots.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace iChip.Hotspots.Controllers
{
    public class AdminController : Controller
    {
        private readonly BO.BOs _bo = new BO.BOs();
        //
        // GET: /Admin/
        public ActionResult Index()
        {
            return View();
        }

        #region Hotspot
        public ActionResult Hotspots(int? index)
        {
            var model = new List<HotspotsObject>();
            int pageSize = 20;
            int pageIndex = index.GetValueOrDefault();
            if (pageIndex == 0)
            {
                pageIndex = 1;
            }
            model = _bo.Select_Hotspots_Paging(pageIndex, pageSize);          
                       

            return View(model);
        }

        [AllowAnonymous]
        public ActionResult AddHotspots(int? Hotspot_id)
        {
         
            var model = new HotspotsModel();
            model.Account_Id = 0; // Account_Id sẽ được lấy từ session từ Login, tạm thời để mặc định =0
           if (Hotspot_id.GetValueOrDefault() > 0)
            {
                var obj = _bo.Select_Hotspots_by_Id(Hotspot_id.GetValueOrDefault());
                if (obj != null)
                {
                    model = new HotspotsModel
                    {
                        Hotspot_Address = obj.Hotspot_Address,
                        Hotspot_City = obj.Hotspot_City,
                        Hotspot_Ip = obj.Hotspot_Ip,                        
                        Hotspot_Mac = obj.Hotspot_Mac,
                        Hotspot_Name = obj.Hotspot_Name,
                        Hotspot_Nasid = obj.Hotspot_Nasid,
                        Hotspot_Region = obj.Hotspot_Region,
                        Hotspot_Status = obj.Hotspot_Status,
                        Hotspot_Type = obj.Hotspot_Type,
                        Hotspot_Id = obj.Hotspot_Id,
                        
                    };
                    if(!string.IsNullOrEmpty(obj.Hotspot_Location) && obj.Hotspot_Location.IndexOf(",")>0)
                    {
                        string[] arr = obj.Hotspot_Location.Split(",".ToCharArray());
                        model.Hotspot_Lat = arr[0].Trim();
                        model.Hotspot_Long = arr[1].Trim();
                    }
                    else
                    {
                        model.Hotspot_Long = "105.800534";
                        model.Hotspot_Lat = "21.013285";
                    }

                   
                    
                }
                ViewBag.State = 1; // cap nhat
            }
            else
            {
                ViewBag.State = 0; // them moi
            }
            IEnumerable<iChip.Hotspots.Commons.Enums.Region> region = Enum.GetValues(typeof(iChip.Hotspots.Commons.Enums.Region)).Cast<iChip.Hotspots.Commons.Enums.Region>();
            model.Hotspot_RegionList  = region.Select(m => new SelectListItem
                {
                    Text = iChip.Hostpots.Commons.Functions.GetDescriptionFromEnumValue<iChip.Hotspots.Commons.Enums.Region>(m),
                    Value = iChip.Hostpots.Commons.Functions.GetDescriptionFromEnumValue<iChip.Hotspots.Commons.Enums.Region>(m)
                });

            //city
            IEnumerable<iChip.Hotspots.Commons.Enums.City> city = Enum.GetValues(typeof(iChip.Hotspots.Commons.Enums.City)).Cast<iChip.Hotspots.Commons.Enums.City>();
            model.Hotspot_CityList = city.Select(m => new SelectListItem
            {
                Text = iChip.Hostpots.Commons.Functions.GetDescriptionFromEnumValue<iChip.Hotspots.Commons.Enums.City>(m),
                Value = iChip.Hostpots.Commons.Functions.GetDescriptionFromEnumValue<iChip.Hotspots.Commons.Enums.City>(m)
            });
            //ViewBag.Region = new SelectList(region);
            return PartialView(model);
        }

        [HttpPost]
        public JsonResult AddHotspots(HotspotsModel model)
        {
            string mess = string.Empty;
            bool flag = false;
            if (model.Hotspot_Id > 0)//cập nhật
            {
                flag = _bo.Update_Hotspots(model, out mess); 
            }
            else //thêm mới
            {
                flag = _bo.Insert_Hotspots(model, out mess);
            }           
            return Json(new { Status = flag, Message = mess });
        }

        /// <summary>
        /// Update LiveTime của Hotspots
        /// Thiết bị hotspot sẽ gọi đến hàm này
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
    
        public bool UpdateLiveTimeHotspot(string mac,string nasId="")
        {
            string ip = iChip.Hostpots.Commons.Functions.GetIPAddress();
            string mess = string.Empty;
            bool flag = false;
            if (mac != "")
            {
                flag = _bo.Update_Hotspots_LiveTime(mac,ip,nasId, out mess);
            }         
            //return Json(new { Status = flag, Message = mess });
            return flag;
        }

        /// <summary>
        /// Gửi Email khi có hotspot down
        /// </summary>
        /// <returns></returns>
        public bool Select_Hotspots_Down()
        {
            try
            {
                var model = new List<HotspotsObject>();
                model = _bo.Select_Hotspots_Down();
                string body = "";
                if (model.Count <= 0) return false;
                foreach (var item in model)
                {
                    body = body + "+ Hotspot <strong>" + item.Hotspot_Name + "</strong> ở địa chỉ <strong>" + item.Hotspot_Address + "</strong> đã bị down khoảng 10 phút trước.<br/>";
                }
                body = body + "Đề nghị quản trị viên kiểm tra lại";
                iChip.Hostpots.Commons.Functions.SendMail(body);
                return true;
            }
            catch
            { return false; }

        }

        /// <summary>
        /// Gen ra bản đồ Hotspots
        /// </summary>
        /// <returns></returns>
        public ActionResult GenMapHotspots()
        {
            var model = new List<MapObject>();
            var objHotspot = _bo.Select_Hotspots();
            if(objHotspot!=null)
            {
                foreach(var item in objHotspot)
                {
                    string longitude = "0", latitude="0";
                    if (!string.IsNullOrEmpty(item.Hotspot_Location) && item.Hotspot_Location.IndexOf(",")>0)
                    {
                        var loglat = item.Hotspot_Location.Split(",".ToCharArray());
                        if(loglat.Length==2)
                        {
                            longitude = loglat[0].Trim();
                            latitude = loglat[1].Trim();
                        }
                    }
                    model.Add(new MapObject
                    {
                        DisplayName = item.Hotspot_Name,
                        Address = item.Hotspot_Address,
                        GeoLong = longitude,
                        GeoLat = latitude,
                        Status = item.Hotspot_Status.ToString()
                    });
                }
            }
            string strJson = JsonConvert.SerializeObject(model);
            ViewBag.Markers = strJson;
            return PartialView(model);
        }

        [HttpPost]
        public JsonResult DeleteHotspot(int hotspot_id)
        {
            string mess = string.Empty;
            bool flag = false;

            try
            {
                _bo.Delete_Hotspots(hotspot_id);
                flag = true;
            }
            catch(Exception ex)
            {
                mess = ex.Message;
                flag = false;
            }

            return Json(new { Status = flag, Message = mess });
        }
       
        #endregion

        #region Splashs
        public ActionResult Splashs(int Hotspot_id, string Hotspot_mac, int? index)
        {
            var model = new List<Splash>();
            int pageSize = 20;
            int pageIndex = 1;
            if (index.GetValueOrDefault() > 0)
            {
                pageIndex = index.GetValueOrDefault();
            }
            model = _bo.Select_Splash_Paging(pageIndex, pageSize, Hotspot_id);
            ViewBag.Hotspot_Mac = Hotspot_mac;
            ViewBag.Hotspot_Id = Hotspot_id;
            return View(model);
        }

        public ActionResult AddSplash(string returnUrl, int Hotspot_id, string Hotspot_mac, int? splash_Id)
        {
            var model = new SplashModel
            {
                Hotspot_Id = Hotspot_id,
                Hotspot_Mac = Hotspot_mac,
                Splash_Id = splash_Id.GetValueOrDefault()
            };
            if (splash_Id.GetValueOrDefault() > 0)
            {
                model = _bo.Select_Splash_by_Id(splash_Id.GetValueOrDefault());
            }

            IEnumerable<iChip.Hotspots.Commons.Enums.UserType> userType = Enum.GetValues(typeof(iChip.Hotspots.Commons.Enums.UserType)).Cast<iChip.Hotspots.Commons.Enums.UserType>();

            model.User_TypeList = userType.Select(m => new SelectListItem
            {
                Text = iChip.Hostpots.Commons.Functions.GetDescriptionFromEnumValue<iChip.Hotspots.Commons.Enums.UserType>(m),
                Value = ((int)m).ToString()
            });

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public async Task<ActionResult> AddSplash(SplashModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                bool flag = false;
                if (model.Splash_Id > 0)
                {
                    flag = _bo.Update_Splashs(model);
                }
                else
                {
                    flag = _bo.Insert_Splashs(model);
                }

                return Redirect(returnUrl);
            }

            return View(model);
        }

        [HttpPost]
        public JsonResult DeleteSplash(int splash_id)
        {
            string mess = string.Empty;
            bool flag = false;

            try
            {
                _bo.Delete_Splashs(splash_id);
                flag = true;
            }
            catch (Exception ex)
            {
                mess = ex.Message;
                flag = false;
            }

            return Json(new { Status = flag, Message = mess });
        }

        #endregion

        #region Method
        
        [HttpPost]
        public ActionResult PostInfo(List<RequestPostField> objRequest, string mac)
        {
            try
            {
                _bo.Insert_Values(mac, objRequest);
                return Json(new { Status = 1, Message = string.Empty });
            }
            catch (Exception ex)
            {
                return Json(new { Status = 0, Message = ex.Message });
            }


        }

        public ActionResult FieldCreate(int method_id, string returnUrl)
        {
            ViewBag.MethodId = method_id;
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        public ActionResult FieldCreated(List<RequestPostField> objRequest, List<FieldValue> objRequestFieldValue)
        {
            try
            {
                _bo.Insert_Fields(objRequest, objRequestFieldValue);
                return Json(new { Status = 1, Message = string.Empty });
            }
            catch (Exception ex)
            {
                return Json(new { Status = 0, Message = ex.Message });
            }

        }

        public ActionResult GenField()
        {
            var model = new FieldModel();
            IEnumerable<iChip.Hotspots.Commons.Enums.FieldType> fieldType = Enum.GetValues(typeof(iChip.Hotspots.Commons.Enums.FieldType))
                                                       .Cast<iChip.Hotspots.Commons.Enums.FieldType>();
          
            //model.Field_Type = fieldType.Select(m => new SelectListItem
            //{
            //    Text = m.ToString(),
            //    Value = ((int)m).ToString()
            //});

            return PartialView(model);
        }

        public ActionResult DefaultField()
        {
            var model = new Field();
            //IEnumerable<iChip.Hotspots.Commons.Enums.FieldType> fieldType = Enum.GetValues(typeof(iChip.Hotspots.Commons.Enums.FieldType))
            //                                           .Cast<iChip.Hotspots.Commons.Enums.FieldType>();
         
            //model.Field_Type = fieldType.Select(m => new SelectListItem
            //{
            //    Text = m.ToString(),
            //    Value = ((int)m).ToString()
            //});

            return View(model);
        }

        public ActionResult ListMethods(int splash_id, string returnUrl)
        {
            var model = new List<Method>();
            model = _bo.Select_Method_by_SplashId(splash_id);
            ViewBag.ReturnUrl = returnUrl;
            return PartialView(model);
        }

        public ActionResult AddMethod(int? splash_id)
        {
            var model = new FieldModel();
            
            if(splash_id.GetValueOrDefault()>0)
            {
                model = _bo.Select_Method_Field_by_SplashId(splash_id.GetValueOrDefault());
            }
            ViewBag.Splash_Id = splash_id.GetValueOrDefault();

            IEnumerable<iChip.Hotspots.Commons.Enums.FieldType> fieldType = Enum.GetValues(typeof(iChip.Hotspots.Commons.Enums.FieldType)).Cast<iChip.Hotspots.Commons.Enums.FieldType>();

            model.Field_Type = fieldType.Select(m => new SelectListItem
            {
                Text = iChip.Hostpots.Commons.Functions.GetDescriptionFromEnumValue<iChip.Hotspots.Commons.Enums.FieldType>(m),
                Value = ((int)m).ToString()
            });

            return View(model);
        }

        [HttpPost]
        [AllowAnonymous]
    
        [ValidateInput(true)]
        public ActionResult AddMethod(List<Method> model)
        {
            try
            {
                if (model == null || model.Count == 0)
                {
                    return Json(new { Status = false, Message = "Không lấy được thông tin form!" });
                }
                else
                {
                    foreach (var item in model)
                    {
                        _bo.Update_Methods(item);
                    }

                    return Json(new { Status = true, Message = "Cập nhật thành công!" });
                }
            }catch(Exception ex)
            {
                return Json(new { Status = false, Message = ex.Message });
            }
        }
        #endregion

        #region Field
        /// <summary>
        /// Gen dong FieldValue
        /// </summary>
        /// <returns></returns>
        public ActionResult GenFieldSurvey()
        {
            var model = new Field();
            IEnumerable<iChip.Hotspots.Commons.Enums.FieldType> fieldType = Enum.GetValues(typeof(iChip.Hotspots.Commons.Enums.FieldType)).Cast<iChip.Hotspots.Commons.Enums.FieldType>();

            ViewBag.Field_Type = fieldType.Select(m => new SelectListItem
            {
                Text = m.ToString(),
                Value = ((int)m).ToString()
            }).ToList();
            
            return PartialView(model);
        }

        [HttpPost]
        public JsonResult RemoveField(int fieldId)
        {
            bool flag = true;
            string mess = string.Empty;
            try
            {                
                flag = _bo.Delete_Field_by_Id(fieldId);
            }
            catch(Exception ex)
            {
                mess = ex.Message;
                flag = false;
            }
            return Json(new { Status = flag, Message = mess });
        }

        [HttpPost]
        public ActionResult GenFieldValueSurvey(int fieldId)
        {
            var model = new List<FieldValue>();
            model = _bo.Select_FieldValue_by_FieldId(fieldId);
            return PartialView(model);
        }

        public ActionResult GenFieldValueSurveyOther(int fieldId)
        {
            var model = new FieldValue();
            model.Field_Id = fieldId;
            return PartialView(model);
        }

        #endregion

        #region Logs
        public ActionResult Logs(int? index)
        {
            var model = new List<Log>();
            int pageSize = 20;
            int pageIndex = index.GetValueOrDefault();
            if (pageIndex == 0)
            {
                pageIndex = 1;
            }
            model = _bo.Select_Logs_Paging(pageIndex, pageSize);

            return View(model);
        }

        public ActionResult Chart_LogByDay()
        {
            var model = new List<Chart_LogByDay>();
            var objChartLog = _bo.Select_Logs_GroupBy_Day(DateTime.Now.Month, DateTime.Now.Year);
            string data = "[" ;
            for (int i = 1; i <= 31; i++)
            {
                
                int total=0;
                if (objChartLog != null)
                {
                    foreach (var item in objChartLog)
                    {
                       if(item.Date == i) total = item.Total;
                    }
                }
             data = data + "[" + i + ","+total+"],";
              
            }

            data = data + "]";
            data = data.Replace("],]", "]]");

            string strJson = data;

            ViewBag.Chart = strJson;
            return PartialView(model);
          
        }
        
        
        #endregion

        #region Brander

        #endregion

        #region Account
        public ActionResult AddAccount()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> AddAccount(AccountModel model)
        {
            if (ModelState.IsValid)
            {
                var strPass = Functions.MD5Hash(model.Password);
                model.Password = strPass;
                _bo.Insert_Accounts(model);
            }
            return View(model);
        }

        #endregion
    }
}